//-----------------------------------------------------------------------------
//  
//  Copyright (c) 2013
//
//  Project  : 
//  Module   : 
//  Parent   : 
//
//  Description: 
//
//
//  Notes       : 
//


module CPU_INTERFACE(
   input                  GTM_RESET,

   input[15:0]            CPU_ADDRESS,
   input                  CPU_CSN,
   input                  CPU_WRN,
   inout[15:0]            CPU_DATA,

   input                  GMPI_CLK,
   output reg[15:0]       GMPI_A,
   output reg[15:0]       GMPI_WD,
   output reg             GMPI_WE,
   output reg             GMPI_CS_BKP,
   input[15:0]            GMPI_RD_BKP
   ) ;

reg[3:0]                  GMPI_WR_SFREGS;
reg[15:0]                 GMPI_CPU_DATA_DRIVE;

always @(posedge GTM_RESET or posedge GMPI_CLK) begin
   if (GTM_RESET==1'b1)
      GMPI_WR_SFREGS[3:0]                           <= 4'd0;
   else begin
      GMPI_WR_SFREGS[0]                             <= (CPU_CSN==1'b0 && CPU_WRN==1'b0);
      GMPI_WR_SFREGS[1]                             <= GMPI_WR_SFREGS[0];
      GMPI_WR_SFREGS[2]                             <= GMPI_WR_SFREGS[1];
      GMPI_WR_SFREGS[3]                             <= GMPI_WR_SFREGS[2];
   end
end

always @(posedge GTM_RESET or posedge GMPI_CLK) begin
   if (GTM_RESET==1'b1)
      GMPI_WE                                       <= 1'b0;
   else begin
      GMPI_WE                                       <= GMPI_WR_SFREGS[3]==1'b0 && GMPI_WR_SFREGS[2]==1'b1;
   end
end
always @(posedge GTM_RESET or posedge GMPI_CLK) begin
   if (GTM_RESET==1'b1) begin
      GMPI_A[15:0]                                  <= 16'd0;
      GMPI_WD[15:0]                                 <= 16'd0;
      GMPI_CS_BKP                                   <= 1'b0;
   end
   else begin
      GMPI_A[15:0]                                  <= CPU_ADDRESS[15:0];
      GMPI_WD[15:0]                                 <= CPU_DATA[15:0];
      GMPI_CS_BKP                                   <= ( CPU_CSN==1'b0 ) && CPU_ADDRESS[15:8]==8'h0F;
   end
end

always @(CPU_CSN or CPU_WRN or GMPI_CS_BKP or GMPI_RD_BKP) begin
   if ( CPU_CSN==1'b0 && CPU_WRN==1'b1 ) begin
      if ( GMPI_CS_BKP==1'b1 )
         GMPI_CPU_DATA_DRIVE[15:0]                <= GMPI_RD_BKP[15:0];
      else
         GMPI_CPU_DATA_DRIVE[15:0]                <= 16'd0;
   end
   else begin
         GMPI_CPU_DATA_DRIVE[15:0]                <= 16'hzzzz;
   end
end
  assign CPU_DATA[15:0]   = GMPI_CPU_DATA_DRIVE[15:0];

endmodule
